<template>
  <div class="article_list">
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh" :success-duration="1500" :success-text="tipText">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :error.sync="error"
        error-text="请求失败，点击重新加载">
        <!-- <van-cell v-for="item in list" :key="item.art_id" :title="item.title" /> -->
        <ArtlistItem :article="item" v-for="item in list" :key="item.art_id" :title="item.title"></ArtlistItem>
      </van-list>
    </van-pull-refresh>

  </div>
</template>

<script>
import { getArticleList } from '@/app/artlist.js'
import ArtlistItem from '@/components/artlist_item.vue'
export default {
  name: 'artlist',
  // 父传子在子组件获取获取，避免多次获取，根据id获取数据
  // vant 组件list 列表加载
  props: {
    channelId: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      // 时间戳
      pre_timestamp: Date.now(),

      // 下拉加载
      isLoading: false,
      //  // /加载失败的状态
      error: false,
      // 加载提示文本
      tipText: ''
    }
  },
  methods: {
    // 数据加载的时候触发 onLoad
    async onLoad () {
      try {
        const res = await getArticleList({
          // 参数
          channel_id: this.channelId,
          timestamp: this.pre_timestamp,
          with_top: 0
        })
        if (Math.random() > 0.5) {
          console.lg(123)
        }
        // 把数据push到list里面
        this.list.push(...res.data.data.results)
        // 时间戳
        this.pre_timestamp = res.data.data.pre_timestamp
        // 当数据第一次加载数据的时候显示提示
        this.loading = false
        console.log(res)
        // 如果数据没有就显示
        if (!res.data.data.results.length) {
          this.finished = true
        }
      } catch (error) {
        // this.$toast('获取数据')
        // 开启错误提示
        this.error = true
        // 关闭加载状态
        this.loading = false
      }
    },
    // 下拉的时候触发
    async onRefresh () {
      try {
        const res = await getArticleList({
          // 参数
          channel_id: this.channelId,
          timestamp: Date.now(),
          with_top: 0
        })
        // 下拉时失败
        if (Math.random() > 0.5) {
          console.lg(1111)
        }
        // 将刷新的数据追加到list前
        this.list.unshift(...res.data.data.results)
        // 关闭时光加载状态
        this.isLoading = false
        this.tipText = '共加载了' + res.data.data.results.length + '条数'
      } catch (err) {
        this.tipText = '加载失败了'
      }
    }

  },
  computed: {},
  watch: {},
  filters: {},
  components: {
    ArtlistItem
  },
  created () { },
  mounted () { }
}
</script>

<style scoped lang='less'>
.article_list {
  height: 100vh;
  overflow: scroll;
}
</style>
